import requests
import json
import uuid

# === 配置您的文心智能体信息 ===
APP_ID = "tQiVHUZSgK5pLEZJPnwLpnAcF3cGQ77b"
SECRET_KEY = "8fNO1uJdeXit8Dny1gP822EZ8jvaVWF3"
AGENT_API_URL = "https://agentapi.baidu.com/assistant/getAnswer"

class WenxinAgent:
    def __init__(self):
        self.app_id = APP_ID
        self.secret_key = SECRET_KEY
        self.open_id = f"user_{str(uuid.uuid4())[:8]}" # 生成随机用户ID
        self.thread_id = None # 用于保持多轮对话上下文

    def chat(self, user_input):
        """
        发送文本消息给智能体，并获取回复
        """
        url = f"{AGENT_API_URL}?appId={self.app_id}&secretKey={self.secret_key}"
        
        payload = {
            "message": {
                "content": {
                    "type": "text",
                    "value": { "showText": user_input }
                }
            },
            "source": self.app_id,
            "from": "openapi",
            "openId": self.open_id
        }

        # 携带上下文 ID
        if self.thread_id:
            payload["threadId"] = self.thread_id

        headers = {'Content-Type': 'application/json'}

        try:
            response = requests.post(url, headers=headers, data=json.dumps(payload))
            res_data = response.json()

            if res_data.get("status") == 0:
                data_body = res_data.get("data", {})
                self.thread_id = data_body.get("threadId") # 更新会话ID
                
                # 提取返回文本
                contents = data_body.get("content", [])
                result_text = ""
                for item in contents:
                    if item.get("dataType") in ["text", "markdown"]:
                        val = item.get("data")
                        if isinstance(val, dict):
                            result_text += val.get("text", "")
                        elif isinstance(val, str):
                            result_text += val
                return result_text if result_text else "智能体思考中..."
            else:
                return f"接口错误: {res_data.get('message')}"

        except Exception as e:
            return f"网络请求异常: {str(e)}"